﻿#include "DeviceLinker.h"
#include "ui_DeviceLinker.h"
#include <sstream>
#include <QSerialPortInfo>
#include <QRadioButton>
#include "QLogTool.h"

using namespace std;

DeviceLinker::DeviceLinker(QWidget *parent) : QDialog(parent), ui(new Ui::DeviceLinker)
{
    ui->setupUi(this);
    m_timr = make_unique<QTimer>(this);
    connect(m_timr.get(), SIGNAL(timeout()), this, SLOT(InterfaceUpdate()));
    m_timr->start(static_cast<int>(UI_PERIOD));
    ui->lb_RxCount->setWordWrap(true);
}

DeviceLinker::~DeviceLinker()
{
    ClearComCollectionWidget();
    delete ui;
}

void DeviceLinker::InterfaceUpdate()
{
    SlotRefresh(); // 刷新可用端口信息
    DevInfoRefresh(); // 刷新设备相关信息
}

// 过滤明显不可用的端口
static bool IsValidCom(const string& comInfo)
{
    const string invalidSymbol = "蓝牙链接上的标准串行";
    return comInfo.find(invalidSymbol) == comInfo.npos;
}

void DeviceLinker::SlotRefresh()
{
    auto collection = QSerialPortInfo::availablePorts();
    if (m_comCountHis == collection.size()) { // 零拷贝检测端口变更
        return;
    }
    m_comCountHis = collection.size();
    // 刷新UI
    ClearComCollectionWidget();
    for (const auto& o : collection) {
        // 新建多选框
        QLabel* option = new QLabel();
        QString optName = o.portName() + " : " + o.description();
        option->setText(optName);
        option->setEnabled(IsValidCom(optName.toStdString()));
        option->installEventFilter(this);
        option->setFont(QFont("Microsoft Yahei", 9));
        CfgOptionStyle(option);
        ui->ComCollectionLayout->addWidget(option);
    }
}

void DeviceLinker::DevInfoRefresh()
{
    if (m_stat == nullptr) {
        ui->btDevLink->setText("开关端口");
        ui->lb_RxCount->clear();
        return;
    }
    static char infoStr[256] = {0};
    double uploadRate = m_stat->dRxBytes() * 1000.0 / UI_PERIOD;
    sprintf(infoStr, "Rx\ntotal[%5llu]\nerr[%.1f]\nbuf[%.1f | %3llu]\npkg[%llu]\n⬆%8.1f B/s",
            m_stat->rxBytes, m_stat->rxErrorRate(), m_stat->rxLoadRate(),
            m_stat->bytesAvailable, m_stat->rxPkg, uploadRate);
    ui->lb_RxCount->setText(QString(infoStr));
    // 根据端口状态决定按钮文本
    string text = m_stat->isPortReady ? "关闭" + m_stat->portName : "打开端口";
    ui->btDevLink->setText(QString::fromStdString(text));
}


void DeviceLinker::ClearComCollectionWidget()
{
    m_selectedOpt.clear();
    qDeleteAll(ui->ComCollection->findChildren<QLabel *>());
}

void DeviceLinker::on_btFrame_accepted()
{
    QString comName = GetOptionName();
    if (comName == "") {
        return;
    }
    emit SigLinkCmd(comName, LINK_OPEN);
}

void DeviceLinker::on_btDevLink_clicked()
{
    QString comName = GetOptionName();
    if (comName == "") {
        return;
    }
    LINK_CMD_TYPE cmdType = LINK_TOGGLE;
    if (m_stat != nullptr) {
        cmdType = m_stat->isPortReady ? LINK_CLOSE : LINK_OPEN;
    }
    emit SigLinkCmd(comName, cmdType);
}

void DeviceLinker::CfgOptionStyle(QLabel* opt)
{
    if (opt == nullptr) {
        return;
    }
    opt->setStyleSheet("QLabel{border:1px solid #242424; color:#C0C0C0; background-color: #444444;}"
                       "QLabel:hover{border:1px solid #242424; color:#000000; background-color: #44D52C;}"
                       "QLabel:disabled{border:0px solid #242424; color:#BFBFBF; background-color: #666666;}"
                       );
}

bool DeviceLinker::eventFilter(QObject *watched, QEvent *event)
{
    auto optCollection = ui->ComCollection->findChildren<QLabel *>();
    for (auto o : optCollection) {
        if (!o->isEnabled()) {
            continue;
        }
        if (o == watched) {
            if (event->type() == QEvent::MouseButtonPress) {
                // 按下效果
                o->setStyleSheet("QLabel{border:2px solid #242424; color:#000000; background-color: #29801A;}");
                CfgOptionStyle(m_lastLabel); // 恢复上次选中的选项
                m_lastLabel = o;
            }
            if (event->type() == QEvent::MouseButtonRelease) {
                // 选取当前选项
                o->setStyleSheet("QLabel{border:2px solid #242424; color:#000000; background-color: #44D52C;}");
                m_selectedOpt = o->text().toStdString();
            }
            if (event->type() == QEvent::MouseButtonDblClick) {
                // 选取当前选项并关闭对话框
                o->setStyleSheet("QLabel{border:2px solid #242424; color:#000000; background-color: #44D52C;}");
                m_selectedOpt = o->text().toStdString();
                on_btDevLink_clicked();
                this->close();
            }
        }
    }
    return QWidget::eventFilter(watched, event);
}

QString DeviceLinker::GetOptionName() const
{
    if (m_selectedOpt == "" || m_selectedOpt.empty()) {
        return "";
    }
    string strComInfo = m_selectedOpt;
    istringstream ss(strComInfo);
    string comName;
    ss >> comName;
    return QString::fromStdString(comName);
}